package com.usabb.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public final class ListUtils extends CollectionUtils {

    public static <T> List<T> getFromTo(List<T> elements, int from, int to) {
        if (isEmpty(elements)) {
            return elements;
        }

        final int size = elements.size();
        if (from > size || to > size) {
            return elements;
        }

        return elements.subList(from, to);
    }

    public static <T> List<List<T>> slice(List<T> elements, Integer[] slices) {
        final List<Integer> integers = Arrays.stream(slices).map(it -> it.intValue()).collect(Collectors.toList());

        return slice(elements, integers);
    }

    public static <T> List<List<T>> slice(List<T> elements, int[] slices) {
        List<List<T>> result = new ArrayList<>(slices.length);

        //slices.length 几片; slices[i] 每片元素个数;
        int pre = 0;
        for (int i = 0; i < slices.length; i++) {  //几片
            //log.info("pre: {},  i:{}", pre,  i);
            if (i==0) {
                result.add(elements.subList(pre, slices[i]));
            } else {
                //log.info(" ------ slices[{}]={}, slices[{}]={}", pre,  slices[pre], i, slices[i]);
                result.add(elements.subList(slices[pre], (slices[pre] + slices[i])) );
            }
            pre = i;
        }
        return result;
    }

    public static <T> List<List<T>> slice(List<T> elements, List<Integer> slices) {
        List<List<T>> result = new ArrayList<>(slices.size());
        //slices.length 几片; slices[i] 每片元素个数;
        int pre = 0;
        for (int i = 0; i < slices.size(); i++) {  //几片
            if (i==0) {
                result.add(elements.subList(pre, slices.get(i)));
            } else {
                result.add(elements.subList(slices.get(pre), (slices.get(pre) + slices.get(i))) );
            }
            pre = i;
        }
        return result;
    }


}
